/**
 * 常用方法封装 请求，文件上传等
 * @author echo. 
 **/
// #ifdef MP
	
// #endif
const tui = {
	//接口地址
	interfaceUrl: function() {
		// return 'http://rabbit.rjzmpp.com/data/'
		// return 'http://shop.wyc168.com/api/'
		return 'https://qcmxnew.wyc168.com/data/'
	},
	faceUrl: function() {
		// return 'http://rabbit.rjzmpp.com/data/'
		return 'http://sh.wyc168.com/'
	},
	toast: function(text, duration, success) {
		uni.showToast({
			title: text || "出错啦~",
			icon: success ? 'success' : 'none',
			duration: duration || 2000
		})
	},
	modal: function(title, content, showCancel, callback, confirmColor, confirmText) {
		uni.showModal({
			title: '提示',
			content: content,
			showCancel: showCancel,
			cancelColor: "#555",
			confirmColor: confirmColor || "#5677fc",
			confirmText: confirmText || "确定",
			success(res) {
				if (res.confirm) {
					callback && callback(true)
				} else {
					callback && callback(false)
				}
			}
		})
	},
	isAndroid: function() {
		const res = uni.getSystemInfoSync();
		return res.platform.toLocaleLowerCase() == "android"
	},
	constNum: function() {
		let time = 0;
		// #ifdef APP-PLUS
		time = this.isAndroid() ? 300 : 0;
		// #endif
		return time
	},
	delayed: null,
	/**
	 * 请求数据处理
	 * @param string url 请求地址
	 * @param string method 请求方式
	 *  GET or POST
	 * @param {*} postData 请求参数
	 * @param bool isDelay 是否延迟显示loading
	 * @param bool isForm 数据格式
	 *  true: 'application/x-www-form-urlencoded'
	 *  false:'application/json'
	 * @param bool hideLoading 是否隐藏loading
	 *  true: 隐藏
	 *  false:显示
	 */
	request: function(url, method, postData, isDelay, isForm, hideLoading) {
		//接口请求
		let loadding = false;
		tui.delayed && uni.hideLoading();
		clearTimeout(tui.delayed);
		tui.delayed = null;
		if (!hideLoading) {
			tui.delayed = setTimeout(() => {
				uni.showLoading({
					mask: true,
					title: '请稍候...',
					success(res) {
						loadding = true
					}
				})
			}, isDelay ? 1000 : 0)
		}
		
		
		// console.log(url)
		// uni.setStorageSync("d_token", 'edc981aedeef7b8892070b0a7f67b27d')
		// uni.setStorageSync("d_token", '01931e675a763db0b619c337052f6d7e')
		
		return new Promise((resolve, reject) => {
			uni.request({
				url: tui.interfaceUrl() + url,
				data: postData,
				header: {
					// 'content-Type': 'application/json',
					'content-type':'application/x-www-form-urlencoded',
					'authorization': tui.getToken(),
				},
				method: method, //'GET','POST'
				dataType: 'json',
				success: (res) => {
					console.log(res)
					clearTimeout(tui.delayed)
					tui.delayed = null;
					if (loadding && !hideLoading) {
						uni.hideLoading()
					}
					if(res.data.code==1){
						resolve(res.data)
					} else if (res.data.code ==401) {
						uni.clearStorageSync()
						tui.wetLogin()
						// tui.toast('登录失效,请重新登录')
						// setTimeout(function(){
						// 	uni.redirectTo({
						// 		url: '/pages/login/login'
						// 	})
						// },1000)
						return
					}else if (res.data.code==407){
						tui.toast(res.data.info)
						setTimeout(function(){
							tui.href('/pages/MyOrderList/MyOrderList?type=0')
						},1000)
					}else{
						tui.toast(res.data.info)
						if(res.data.info=="收款方式不能为空"){
							setTimeout(function(){
								tui.href('/pages/bank/bank_list_1')
							},1000)
						}
					}
				},
				fail: (res) => {
					clearTimeout(tui.delayed)
					tui.delayed = null;
					tui.toast("网络不给力，请稍后再试~")
					reject(res)
				}
			})
		})
	},
	/**
	 * 上传文件
	 * @param string url 请求地址
	 * @param string src 文件路径
	 */
	uploadFile: function(url, src) {
		let that = this
		uni.showLoading({
			title: '请稍候...'
		})
		return new Promise((resolve, reject) => {
			const uploadTask = uni.uploadFile({
				url: tui.interfaceUrl() + url,
				filePath: src,
				name: 'file',
				header: {
					'authorization':  tui.getToken(),
				},
				success: function(res) {
					uni.hideLoading()
					let d = JSON.parse(res.data.replace(/\ufeff/g, "") || "{}")
					console.log(d)
					let fileObj = d;
					resolve(fileObj)
				},
				fail: function(res) {
					reject(res)
					that.toast(res.msg);
				}
			})
		})
	},
	tuiJsonp: function(url, callback, callbackname) {
		// #ifdef H5
		window[callbackname] = callback;
		let tuiScript = document.createElement("script");
		tuiScript.src = url;
		tuiScript.type = "text/javascript";
		document.head.appendChild(tuiScript);
		document.head.removeChild(tuiScript);
		// #endif
	},
	//设置用户信息
	setUserInfo: function(mobile,token) {
		//uni.setStorageSync("thorui_token", token)
		uni.setStorageSync("thorui_mobile", mobile)
	},
	//获取token
	getToken() {
		return uni.getStorageSync("d_token")
	},
	//判断是否登录
	isLogin: function() {
		return uni.getStorageSync("d_token") ? true : false
	},
	//跳转页面，校验登录状态
	href(url, isVerify) {
		if (isVerify && !tui.isLogin()) {
			uni.navigateTo({
				url: '/pages/common/login/login'
			})
		} else {
			uni.navigateTo({
				url: url
			});
		}
	},
	dianji(fn) {
	    let that = this;
		let is_true = getApp().globalData.is_true
		console.log(is_true)
	    if (is_true) {
	        getApp().globalData.is_true = false;
	        setTimeout(function () {
	            getApp().globalData.is_true = true;
	        }, 5000)
			fn();
	    } else {
	        //如果一直走else分支可能是你没有在页面的data下面挂载onoff:true,不然一直都会走else
	        console.log("请稍后点击")
	    }
	},
	wetLogin(e,d){
		let that = this
		uni.login({
			provider: 'weixin',
			success: (res) => {
				let data = {code: res.code,inviter_code:uni.getStorageSync('refCode'),openid_inviter_code:uni.getStorageSync('share_openid')}
				tui.request("api.wxapp/session", "POST", data, false, false, true).then((res) => {
					console.log(res)
					tui.toast(res.info)
					uni.removeStorage({
					    key: 'refCode',
					    success: function (res) {
					        console.log('success');
					    }
					});
					uni.setStorageSync('d_token', res.data.token)
					uni.setStorageSync('headimg', res.data.headimg)
					uni.setStorageSync('inviter_code', res.data.inviter_code)
					uni.$emit("isLogin",1)
					if(res.data.is_avatar==2){
						console.log(res.data.is_avatar)
						uni.$emit("isShow",res.data.is_avatar)
					}
					if(e==1){
						tui.getList(d)
					}
				}).catch((res) => {
					that.is_btn = false
				})
			},
		});
	},
	TongjiLive(e,d){
		let that = this
		console.log(e,d+"qweqweqweqweqe")
		if(d==0){
			return
		}
		tui.request("api.auth.live/lookLive", "POST", {type:e,room_id:d}, false, false, true).then((res) => {
			console.log(res)
			if(res.code==1){
				uni.setStorageSync('lookLive', e)
			}
		}).catch((res) => {
			
		})
	},
	getList(e){
		let that = this
		tui.request("api.auth.live/liveRoomMt", "POST", {page:1}, false, false, true).then((res) => {
			if(res.code==1){
				res.data.list.map((item,index)=>{
					if(e==item.id){
						uni.setStorageSync('room_id', item.course_id)
						tui.href('/pages/zhibo/zhibo?url='+encodeURIComponent(JSON.stringify(item.url))+"&image="+item.cover+"&id="+item.id)
					}
				})
				
			}
		}).catch((res) => {
			
		})
	},
	phoneYin(phone){
		if(phone){
			return  phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
		}
	},
	phoneMore(phone){
		var arr = phone.split(',')
		var data =''
		arr.map((item,index)=>{
			data = data+item.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')+','
		})
		data = data.slice(0, -2)
		if(phone){
			return  data;
		}
	},
	setIncrement(val) {
	    let status = false,
	    step = 3.30* val / (1000 / 30),
	    count  = 0,
	    interval = null;
	    interval = setInterval(() => {
	        if(count < val) {
	            count = count + step;
	        } else {
	            status = true
				count = val
	        }
	        if(status) {
	            clearInterval(interval)
	        }
			return count
	    }, 30)
		
	},
	secondsToTime(seconds) {
	  const hours = Math.floor(seconds / 3600);
	  const minutes = Math.floor((seconds % 3600) / 60);
	  const remainingSeconds = seconds % 60;
	  return hours + "时" + minutes + "分" + remainingSeconds + "秒" ;
	},
	autoUpdate() { //更新新版本
	  	var self = this
	  	// 获取小程序更新机制兼容
	  	console.log('canUndate',uni.canIUse('getUpdateManager'))
	  	if (uni.canIUse('getUpdateManager')) {
	  		const updateManager = uni.getUpdateManager()
	  		//1. 检查小程序是否有新版本发布
	  		updateManager.onCheckForUpdate(function(res) {
	  			// 请求完新版本信息的回调
	  			console.log('hasUpdate',res.hasUpdate)
	  			if (res.hasUpdate) {
	  				//检测到新版本，需要更新，给出提示
	  				uni.showModal({
	  					title: '更新提示',
	  					content: '检测到新版本，是否下载新版本并重启小程序？',
	  					success: function(res) {
	  						if (res.confirm) {
	  							//2. 用户确定下载更新小程序，小程序下载及更新静默进行
	  							self.downLoadAndUpdate(updateManager)
	  						} else if (res.cancel) {
	  							//用户点击取消按钮的处理，如果需要强制更新，则给出二次弹窗，如果不需要，则这里的代码都可以删掉了
	  							uni.showModal({
	  								title: '温馨提示~',
	  								content: '本次版本更新涉及到新的功能添加，旧版本无法正常访问的哦~',
	  								showCancel: false, //隐藏取消按钮
	  								confirmText: "确定更新", //只保留确定更新按钮
	  								success: function(res) {
	  									if (res.confirm) {
	  										//下载新版本，并重新应用
	  										self.downLoadAndUpdate(updateManager)
	  									}
	  								}
	  							})
	  						}
	  					}
	  				})
	  			}
	  		})
	  	} else {
	  		// 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
	  		uni.showModal({
	  			title: '提示',
	  			content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
	  		})
	  	}
	  },
	  /**
	   * 下载小程序新版本并重启应用
	   */
	  downLoadAndUpdate(updateManager) {
	  	var self = this
	  	uni.showLoading();
	  	//静默下载更新小程序新版本
	  	updateManager.onUpdateReady(function() {
	  		uni.hideLoading()
	  		//新的版本已经下载好，调用 applyUpdate 应用新版本并重启
	  		updateManager.applyUpdate()
	  	})
	  	updateManager.onUpdateFailed(function() {
	  		// 新的版本下载失败
	  		uni.showModal({
	  			title: '已经有新版本了哟~',
	  			content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~',
	  		})
	  	})
	  },
}

export default tui